package com.mrli.cat.weather.tools;

import android.accounts.Account;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;

import com.mrli.cat.weather.activity.ForecastFragment;
import com.mrli.cat.weather.activity.WeatherPreferenceActivity;
import com.mrli.cat.weather.database.WeatherContract;
import com.mrli.cat.weather.model.City;
import com.mrli.cat.weather.service.WeatherUpdateService;

/**
 * Created by MrLi on 2015/7/5.
 */
public class WriteCityAndUpdate extends AsyncTask<City, Void, Void> {
    private Context mContext;

    public WriteCityAndUpdate(Context context) {
        this.mContext = context;
    }

    @Override
    protected Void doInBackground(City... params) {
        mContext.getContentResolver()
                .delete(
                        WeatherContract.LOCATION_CONTENT_URI,
                        WeatherContract.LocationEntry.COLUMN_NAME + "=?",
                        new String[]{params[0].getmCityName()}
                );
        //写入城市信息到数据库
        ContentValues locaValues = new ContentValues();
        locaValues.put(WeatherContract.LocationEntry.COLUMN_NAME, params[0].getmCityName());
        locaValues.put(WeatherContract.LocationEntry.COLUMN_LAT, params[0].getLat());
        locaValues.put(WeatherContract.LocationEntry.COLUMN_LON, params[0].getLon());
        mContext.getContentResolver().insert(WeatherContract.LOCATION_CONTENT_URI, locaValues);
        //写入城市名到配置文件
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
        sharedPreferences.edit().putString(WeatherPreferenceActivity.LOCAL_CITY, params[0].getmCityName()).apply();
        //更新界面组件
        mContext.startService(new Intent(mContext, WeatherUpdateService.class));
        //请求更新数据
        Account account;
        account = ForecastFragment.CreateSyncAccount(mContext);
        Bundle settingsBundle = new Bundle();
        settingsBundle.putBoolean(
                ContentResolver.SYNC_EXTRAS_MANUAL, true);
        settingsBundle.putBoolean(
                ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        ContentResolver.requestSync(account, WeatherContract.AUTHORITY, settingsBundle);
        return null;
    }
}